const express = require('express');
const bp = require('body-parser');
const path = require('path');



const app = express();
app.listen(80);
console.log('网站服务器启动成功');


// post
app.use(bp.urlencoded({
    extended: false
}));
//开放静态资源 
app.use(express.static(path.join(__dirname, 'public')));

//设置跨域访问
app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
    // //允许的header类型
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    // //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // 可以带cookies
    res.header("Access-Control-Allow-Credentials", true);
    if (req.method == 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});

app.get('/data', (req, res) => {
    res.send('Hello World');
})
// 传统方式
// app.get('/books', (req, res) => {
//     res.send(req.query);
// })
app.get('/books/:id', (req, res) => {
    res.send(req.params.id)
})